﻿ using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using OutdoorLib.BaseEntity.Contract;
using OutdoorLib.BaseEntity.Face;
using Grishko.Tools;
using Grishko.DataTier;
using OutdoorLib.BaseEntity.Filters;
using OutdoorLib.BaseEntity.Constraction;
using System.IO;
using System.Data;
using Grishko.UIControls;

public partial class ContractEditor : MasterPage_EditControl
{

    Func<ListViewDataItem, bool> LvUpdCmd = null;
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        MyInit();
    }    

    protected void Page_Load(object sender, EventArgs e)
    {
        
        if (!IsPostBack)
        {
            AppEnvironment.ObjectFactory.ResetCashe(CurrentID);
            MyDataBind();
        }
        
        SetAlertForTextBox();

    }

    private void MyInit()
    {
        if (null != lvClient.EditItem)
        {
            Grishko.UIControls.Autocomplit text = (Autocomplit)lvClient.EditItem.FindControl("ClientTextComplit");
            text.RowSelected += new EventHandler(lvClient_ComplitRowSelect);
        }

        lvCommonIfo.DataSource = ContractAsList;
        lvClient.DataSource = ContractAsList;
        lvFinResult.DataSource = FinResultAsList;        
        ctlContractSheduleSideList1.ContractSource = GetContractSource;
        ctlContractSideList1.ContractSource = GetContract;
        ctlContractSideList1.SaveMethod = Save;
        

                
        ctlPayments.DataSource = fPayments;
        ctlPayments.OnChangeDataSource = fOnPaymentRowChange;        
        ctlPayments.TypeOfPayents = typeof(TContractPaymentItem_Plan);


        ctlPayables.DataSource = fPayables;
        ctlPayables.OnChangeDataSource = fOnPaymentRowChange;        
        ctlPayables.TypeOfPayents = typeof(TContractPaymentItem_Payables);

        
    }

    #region SideShedule
    [System.Web.Services.WebMethod]
    public static string CallRefreshRow(RefreshRowParam Param)
    {
        return RefreshSheduleRowEngine.RefreshRow((Param)); ;
    }
    private ContractEntity GetContractSource()
    {
        return Contract;
    }
    #endregion

    private bool fOnPaymentRowChange()
    {
        return Save(); 
    }
    private EntityList fPayables()
    {
        if (null == Contract.FinanceInfo)
            return null;

        return Contract.FinanceInfo.Payables;
    }

    private EntityList fPayments()
    { 
        if(null==Contract .FinanceInfo )
            return null;

        return Contract.FinanceInfo.PaymentsPlan;
    }
    private void MyDataBind()
    {        
        
        lvCommonIfo.DataBind();
        lvClient.DataBind();
        lvFinResult.DataBind();
        

        if (mvSideBox.ActiveViewIndex == 1)
            ctlContractSheduleSideList1.DataBind();
        else
            ctlContractSideList1.DataBind();
       
    }

    #region Source
    ContractEntity _Contract = null;
    protected ContractEntity Contract
    {
        get
        {            

            if (null != _Contract)
            {
                    return _Contract;
            }

            if (GlobalConstants.IsNewRecord(CurrentID))
            {
                _Contract = (ContractEntity)AppEnvironment.ObjectFactory.GetNewObject(CurrentTagName, GlobalConstants.GetNewID(CurrentID));
                AppEnvironment.BusinessRules.SetDefaultValue(_Contract, null);
            }
            else
                _Contract = (ContractEntity)AppEnvironment.ObjectFactory.GetObject(CurrentID, CurrentTagName);


            return _Contract;
        }

    }

    protected ContractEntity GetContract()
    {
        return Contract;
    }

    protected List<TFinanceInfo> FinResultAsList 
    {
        get
        {
            List<TFinanceInfo> result = new List<TFinanceInfo>();
            if (null != Contract.FinanceInfo)
                result.Add(Contract.FinanceInfo);
            return result;

        }
    }
    protected List<ContractEntity> ContractAsList 
    {
        get
        {
            
            List<ContractEntity> res = new List<ContractEntity>();
            res.Add(Contract);
            return res;
        }
    }

    protected List<Client> ClientAsList
    {
        get
        {
            List<Client> res = new List<Client>();
            if (null != Contract.Client)
                res.Add(Contract.Client);
          
            return res;
        }
    }
    
    protected List<ListItem> ClientListSource
    {
        get
        {
            List<ListItem> result = new List<ListItem>();
            ClientListFilter l = new ClientListFilter();
            foreach (Client i in l.GetCollection())
            {
                result.Add(new ListItem( i.FullName, i.ID));
            }
            return result;
            
        }
    }
    
    protected List<ListItem> ContractTypeSouce 
    {
        get
        {
//            ListItemCollection result = new ListItemCollection();
            List<ListItem> result = new List<ListItem>();
            foreach (DictionaryItem i in TContractStatus.GetFullList())
            {
                bool bSel=false ;               
                if (null != Contract.ContractStatus)
                    bSel = (Contract.ContractStatus.ID == i.ParamID);
                ListItem li = new ListItem(i.Value.ToString(), i.ParamID);           
                li.Selected = bSel;
                result.Add(li);
            }
            return result;
        }
}
        
    #endregion
    
    #region ListView
    protected void ItemUpdating(object sender, ListViewUpdateEventArgs e)
    {
    }
    protected void ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        if (string.Empty == e.CommandName) return;

        ListView lv = (ListView)sender;

        switch (lv.ID)
        {
            case "lvCommonIfo":
                LvUpdCmd = UpdateCommonIfo;
                break;

            case "lvClient":
                LvUpdCmd = UpdateClient;
                break;
        }

        switch (e.CommandName)
        {
            case "Edit":
                {
                        ListViewDataItem d = (ListViewDataItem)e.Item;
                        lv.EditIndex = d.DataItemIndex;
                    break;
                }
            case "Insert":
                {

                    break;
                }
            case "Update":
                {
                    // обновить поле
                    if (LvUpdCmd((ListViewDataItem)e.Item))
                    {
                        lv.EditIndex = -1;
                        // если бизнес правила в порядке -попытаться неявно сохраниться
                        if (AppEnvironment.BusinessRules.CheckUpdate(Contract).Count == 0)
                        {
                            if (Save())
                                break;

                        }
                        // Если вышли из блока без сохранения - показать предупреждение  
                        ShowAlert();
                    }
                    break;
                }
            case "Delete":
                {
                    //DeleteCustomer(e.CommandArgument as string);
                    break;

                }
        }

        MyDataBind();
        SetAlertForTextBox();



    }
    protected void ItemEditing(object sender, ListViewEditEventArgs e)
    {



    }
    protected void ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        //// Проверить тип строчки - если это строчка редактирования - зацепить требуемый DS

        //ListView lv = (ListView)sender;
        //switch (lv.ID)
        //{
        //    case "lvStatus":
        //        {
        //            object tv = e.Item.FindControl("tvStatus");
        //            if (null != tv)
        //            {
        //                ((TreeView)tv).DataSource = GetEmployeeSource("chTree_Status", "ctl00_cphHead_hf_tvStatus");
        //                ((TreeView)tv).DataBind();

        //            }
        //            break;
        //        }

        //    case "lvCategoria":
        //        {

        //            object tv = e.Item.FindControl("tvCategoria");
        //            if (null != tv)
        //            {
        //                ((TreeView)tv).DataSource = GetCategoriaSource("chTree_Categoria", "ctl00_cphHead_hf_tvCategoria");
        //                ((TreeView)tv).DataBind();

        //            }
        //            break;
        //        }

        //}

    }
    #endregion
    
    #region LvUpdateCommand
    private bool UpdateCommonIfo(ListViewDataItem item)
    {
        // считываем номер дату состояние
        if (null == lvCommonIfo.EditItem)
            return true;
        TextBox t = (TextBox)lvCommonIfo.EditItem.FindControl("txtNumber");
        Contract.Number = t.Text;
        TextBox t1 = (TextBox)lvCommonIfo.EditItem.FindControl("txt_dtContractSign");
        if (!string.IsNullOrEmpty ( t1.Text) ) 
                Contract.ContractStatus .Date =(Convert .ToDateTime (t1.Text ));

        DropDownList  l = (DropDownList)lvCommonIfo.EditItem.FindControl("cmbType");
        Contract.ContractStatus.TypeID = l.SelectedValue;
        Contract.ContractStatus.Name = l.SelectedItem.Text;
        return true;
    }
    private bool UpdateClient(ListViewDataItem item)
    {

        lvClient_ComplitRowSelect(null, null);
        return true;
    }    
    #endregion
    
    protected void cmbType_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    protected void btnSaveCommonInfo_Click(object sender, EventArgs e)
    {
        bool bRedirect = GlobalConstants.IsNewRecord(CurrentID);
        
        if (!Save())
                return;

        if (bRedirect)
            QueryStringTools.RefreshPage(GlobalConstants.qID + "=" + CurrentID);
        
        HideAlert();

    }
    protected void btnSaveExit_Click(object sender, EventArgs e)
    {
        if(Save ())
            QueryStringTools.RefreshPageWitchReturnUrl();
    }


    private bool Save()
    {
        try
        {
            // проверить бизнес правила на вставку/обновление                        
            List<string> CheckResult = AppEnvironment.BusinessRules.CheckUpdate(Contract);

            if (0 == CheckResult.Count)
            {
                AppEnvironment.ObjectFactory.SaveObject(Contract);
                return true;
            }
            else
            {
                AppEnvironment.Helper.RegistredStartUpAlert(this, CheckResult);
                return false;
            }

        }

        catch
        {
            return false;
        }


    }

    protected void EditClient_Click(object sender, ImageClickEventArgs e)
    {
        
        lvClient.EditIndex = 0;
        MyDataBind();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Contract.ContractSideItemList.Clear();
        Contract.Save();

    }
    protected void OnAddClient(object sender, EventArgs e)
    {
        PopPanel_Client.Show();

    }
    protected void btnFinancEdit(object sender, ImageClickEventArgs e)
    {
        if (null == Contract.FinanceInfo)
            Contract.FinanceInfo = new TFinanceInfo();

        popFinance.Show();
        ctlPayables.DataBind();
        ctlPayments.DataBind();
    }
    protected void lvClient_ComplitRowSelect(object sender, EventArgs e)
    {
        if (null == lvClient.EditItem)
            return;

        Grishko.UIControls.Autocomplit text = (Autocomplit)lvClient.EditItem.FindControl("ClientTextComplit");
        if (!string.IsNullOrEmpty(text.IdValue) )
        { 
            Client cl= (Client ) AppEnvironment .Helper .GetObject (text.IdValue);
            cl.PropertyLoad();
            Contract.Client = cl;
        }
        lvClient.EditIndex = -1;
        MyDataBind();

    }

    protected void GridModeChange( object sender , EventArgs arg)
    {
        mvSideBox.ActiveViewIndex = (sender as RadioButtonList).SelectedIndex;
        MyInit();
        MyDataBind();

    }

    #region ClientEditor
    [System.Web.Services.WebMethod]
    public static string GetControl(string sValue)
    {
        TextWriter sw = new StringWriter();
        Html32TextWriter w = new Html32TextWriter(sw);
        List<ListItem> ht = new List<ListItem>();

        SecuretyContext SC = AppContext.GetSC();

        string SQL = "select Objectid,Propertyvalue  from vSrchObjectPropertyStorage where tagname= 'Client' and propertyname='Name'and propertyvalue like '%{0}%'";

        DataSet ds= AppEnvironment. Helper.GetDS (string.Format (SQL,sValue ));
        if (ds == null)
            return string.Empty;

        if (ds.Tables .Count ==0)
            return string.Empty;

        foreach (DataRow rw in ds.Tables[0].Rows)
        {
            ht.Add(new ListItem(rw[1].ToString(), rw[0].ToString()));            
        }
        
        ListBox lc = Grishko.UIControls.Autocomplit.GetListBoxControl(ht);
        lc.RenderControl(w);
        return sw.ToString();
    }
    public string ClientName { get { if (null != Contract.Client) return Contract.Client.Name; else return string.Empty; } }
    public string ClientID { get { if (null != Contract.Client) return Contract.Client.ID ; else return string.Empty; } }
    public string GetbtnAddClient_ID()
    {
        if (null == lvClient.EditItem)
            return string .Empty ;

        ImageButton btn = (ImageButton)lvClient.EditItem.FindControl("btnAddClient");
        return btn.ClientID;
    }
    protected void btnInsertNewClient_Click(object sender, EventArgs arg)
    {
        if (string.IsNullOrEmpty(txtClientName_Insert.Text))
            return;

        Client Client = (Client)AppEnvironment.ObjectFactory.GetNewObject("Client", GlobalConstants.GetNewID(Guid.NewGuid ().ToString () ));
        Client.Name = txtClientName_Insert.Text;
        Client.Curator = AppEnvironment.CurrentEmployeer;
        Client.Adress = txtClientAdress.Text;
        Client.Phones = txtClientPhones.Text;
        Client.Email = txtClientMail.Text;

        // проверить бизнес правила на вставку/обновление                        
        List<string> CheckResult = AppEnvironment.BusinessRules.CheckUpdate(Client);

        if (0 == CheckResult.Count)
        {
            AppEnvironment.ObjectFactory.SaveObject(Client);
            Contract.Client = Client;
            PopPanel_Client.Hide();
            MyDataBind();
            updClient.Update();
        }
        else
        {
            AppEnvironment.Helper.RegistredStartUpAlert(this, CheckResult);            
        }

    }
    #endregion


    protected string GetSrc()
    {
        ClientListFilter f= new ClientListFilter ();

           string sUrl =string.Empty ;


           if (!string.IsNullOrEmpty(ClientID))

                sUrl = AppEnvironment.PageNavigator.GetNewObjectUrlCommand(f.ObjectPageKey,
                                                                        f.Where.EntityTypeTagName,
                                                                        f.AddUrlHandler_Insert);
           else
               sUrl = AppEnvironment.PageNavigator.GetEditObjectUrlCommand(f.ObjectPageKey,
                                                                        ClientID,
                                                                        f.Where.EntityTypeTagName,
                                                                        f.AddUrlHandler_Edit);
     


        return sUrl;
    }

    protected void btnFinInfoClose_Click(object sender, ImageClickEventArgs e)
    {
        popFinance.Hide();
        MyDataBind();
        updFinanceResult.Update();
    }

    
}
